<template>
  <div ref="datepicker" class="it-date-picker">
    <div :class="['inputbox', isDisabled && 'disabled-inputbox']">
      <input
        v-if="isDisabled"
        v-model="showPickerTime"
        class="it-date-picker-input"
        :placeholder="placeholder"
        readonly="readonly"
      />
      <input
        v-else
        v-model="showPickerTime"
        class="it-date-picker-input"
        :placeholder="placeholder"
        readonly="readonly"
        @focus="showPopup"
      />
      <div
        v-show="showPickerTime"
        :class="['clearBtn', isDisabled && 'disabled-clearBtn']"
        @click="clearInput"
      ></div>
      <div
        v-show="!showPickerTime"
        class="picker-icon"
        @click="showPopup"
      ></div>
    </div>

    <div v-if="visible" class="it-date-picker-popover">
      <div v-if="currentComp === 0">
        <PickerDays
          :format-date="pickerTime"
          @time-choose="onPickerChoose"
          @mode-change="modeChange"
        ></PickerDays>
      </div>
      <div v-else-if="currentComp === 1">
        <PickerMonths
          :format-date="pickerTime"
          @time-choose="onPickerChoose"
          @mode-change="modeChange"
        ></PickerMonths>
      </div>
      <div v-else-if="currentComp === 2">
        <PickerYears
          :format-date="pickerTime"
          @time-choose="onPickerChoose"
        ></PickerYears>
      </div>
    </div>
  </div>
</template>

<script name="ItDatepicker" setup>
import { onClickOutside } from '@vueuse/core'
import { creatDate, getYearMonthDay } from './date.js'
import PickerDays from './PickerDays.vue'
import PickerMonths from './PickerMonths.vue'
import PickerYears from './PickerYears.vue'
import { ItMessage } from '@/components'

import { ref, computed, watch } from 'vue'

const props = defineProps({
  mode: {
    type: String,
    default: 'Picker-Days',
    validator: function (value) {
      return (
        ['Picker-Days', 'Picker-Months', 'Picker-Years'].indexOf(value) !== -1
      )
    },
  },
  defaultTime: {
    type: String,
    default: '',
  },
  placeholder: {
    type: String,
    default: '',
  },
  format: {
    type: String,
    default: 'YYYY/MM/DD',
  },
  flag: {
    type: String,
    default: '',
  },
  keyVal: {
    type: String,
    default: '',
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  limit: {
    type: Boolean,
    default: false,
  },
  //限制前推天数
  limitDay: {
    type: Number,
    default: 0,
  },
})

let isDisabled = ref(props.disabled)

let pickerTime = ref(creatDate(props.defaultTime))

if (!props.defaultTime) {
  pickerTime.value = null
}
watch(
  () => props.defaultTime,
  (newTime, oldTime) => {
    if (newTime != oldTime) {
      pickerTime.value = props.defaultTime ? creatDate(props.defaultTime) : null
    }
  }
)

let showPickerTime = computed({
  get() {
    let returnData = ''
    if (pickerTime.value && !isNaN(Date.parse(pickerTime.value))) {
      const [year, month, day] = getYearMonthDay(pickerTime.value)
      switch (props.mode) {
        case 'Picker-Days':
          returnData = `${year}-${
            month + 1 < 10 ? `0${month + 1}` : month + 1
          }-${day < 10 ? `0${day}` : day}`
          break
        case 'Picker-Months':
          returnData = `${year}-${month + 1 < 10 ? `0${month + 1}` : month + 1}`
          break
        case 'Picker-Years':
          returnData = `${year}`
          break
        default:
          break
      }
    } else {
      returnData = ''
    }
    return returnData
  },
})

/**
 * 子组件选择时间
 * 1.1 直接赋值给pickerTime
 * 2.1 day
 *  2.1.1 将showPickerTime传递到父组件
 * 2.2 month
 *   2.2.1 当mode为Picker-Days时,切换mode为Picker-Days;否则将showPickerTime传递到父组件
 * 2.3 year
 *   2.3.1 当mode不为Picker-Years时,切换mode为Picker-Months;否则将showPickerTime传递到父组件
 */
const emits = defineEmits(['change'])

const onPickerChoose = (e) => {
  if (!e) {
    returnChange(showPickerTime.value)
    return
  }
  const [year, month, day] = getYearMonthDay(pickerTime.value)
  const [year1, month1] = getYearMonthDay(e.value)
  switch (e.mode) {
    case 'Picker-Days':
      //时间选择限制 不可选择当天或当天以前的时间
      if (props.limit) {
        //限制时间向前推移   limitDay为天数
        let day = props.limitDay * 86400000
        if (e.value.getTime() <= new Date().getTime() - day) {
          ItMessage({
            content: '选择时间不可以小于当前时间',
          })
          return
        }
      }
      pickerTime.value = e.value
      returnChange(showPickerTime.value)
      break
    case 'Picker-Months':
      {
        const timestamp = `${year}-${month1 + 1}-${day}`
        pickerTime.value = new Date(timestamp)
        if (props.mode == 'Picker-Days') {
          modeChange('Picker-Days')
        } else {
          returnChange(showPickerTime.value)
        }
      }
      break
    case 'Picker-Years':
      {
        const timestamp2 = `${year1}-${month + 1}-${day}`
        pickerTime.value = new Date(timestamp2)
        if (props.mode != 'Picker-Years') {
          modeChange('Picker-Months')
        } else {
          returnChange(showPickerTime.value)
        }
      }
      break
    default:
      break
  }
}
const getDateNum = computed(() => {
  return props.flag
})
const returnChange = (val) => {
  let valArr = val.split('-')
  let format = val ? props.format : ''
  if (val) {
    if (valArr[0]) {
      format = format.replace('YYYY', valArr[0])
    }
    if (valArr[1]) {
      format = format.replace('MM', valArr[1])
    }
    if (valArr[2]) {
      format = format.replace('DD', valArr[2])
    }
  }
  let keyVal = props.keyVal
  if (keyVal) {
    emits('change', format, keyVal, getDateNum.value)
  } else emits('change', format, getDateNum.value)
  closePopup()
}

/**
 * 展示选择器
 * 1. pickerTime赋值
 * 2. 设置mode
 * 3. visible设置为true
 */
let visible = ref(false)
const showPopup = () => {
  pickerTime.value = !isNaN(Date.parse(pickerTime.value))
    ? pickerTime.value
    : props.defaultTime
    ? new Date(props.defaultTime)
    : ''
  setMode(props.mode)
  visible.value = true
}
/**
 * 设置点击其他地方隐藏
 */

const datepicker = ref(null)
onClickOutside(datepicker, () => {
  closePopup()
})
const closePopup = () => {
  if (visible.value) {
    visible.value = false
  }
}

/**
 * 设置mode
 */
const modeMap = new Map([
  ['Picker-Days', 0],
  ['Picker-Months', 1],
  ['Picker-Years', 2],
])
let currentComp = ref(modeMap.get(props.mode))
const setMode = (v) => {
  currentComp.value = modeMap.get(v)
}
/**
 * 切换mode
 */
const modeChange = (v) => {
  setTimeout(() => {
    setMode(v)
    visible.value = true
  })
}

/**
 * 清空input
 * 1.清空pickerTime
 * 2.初始化mode
 */
const clearInput = () => {
  if (props.disabled) return
  else {
    pickerTime.value = null
    onPickerChoose()
  }
}
</script>

<style scoped>
@import url('./data-picker.css');
</style>
